package com.bidevalution.business.impl;

import java.util.List;
import java.util.Map;

import com.bidevalution.service.BidParamService;
import com.qtp.core.model.Response;
import com.qtp.core.util.GsonUtil;
import lombok.extern.log4j.Log4j2;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.bidevalution.business.service.BeBudgetItemService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.business.service.JdbcTemplateService;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.support.util.LogUtil;
import com.bidevalution.support.util.MapUtil;
import org.springframework.transaction.annotation.Transactional;

@Service
public class BeBudgetItemServiceImpl implements BeBudgetItemService {
	@Autowired
	private JdbcTemplateService jdbcTemplateService;
	@Autowired
	private BeSectionInfoService beSectionInfoService;
	@Autowired
	private BidParamService bidParamService;
	private LogUtil log =LogUtil.getLogManager(getClass());
	@Override
	public List<Map<String, Object>> selectAllList(String sectionId, String managerNodeId) {
		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
		// buno_type=2不展示属性 如果要展示属性则 buno_type 不等于0
		return jdbcTemplateService.selectForList(
				"select buno_Code as Code, buno_Name as Name,  buno_Unit as Units, buno_Amount as Amount, buno_Type as NodeType,\r\n"
						+ " buno_BudgetNodeID as NodeID, buno_Idx as Idx, buno_JobIdentity as JobIdentity  from td_BudgetNode \r\n"
						+ " where buno_ProjectID =:projectId and buno_ManageNodeID =:managerNodeId and buno_type=2 order by buno_IdxCode ",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).putValue("managerNodeId",
						managerNodeId).getMap());
	}

	@Override
	public List<Map<String, Object>> selectCheckList(String sectionId) {
		BeSectionInfo beSectionInfo = beSectionInfoService.getBeSectionInfoById(sectionId);
		return jdbcTemplateService.selectForList(
				" select mo.*, b.buno_Code as Code, b.buno_IdxCode  as IdxCode, \r\n" +
						"     b.buno_Name as Name, b.buno_Unit as Units, b.buno_Amount as Amount, \r\n" +
						"     b.buno_JobIdentity as JobIdentity,\r\n" +
						"     mnp.mano_Name as mano_Name, \r\n" +
						"     mn.mano_Code+mn.mano_Name as mano_NameA, mn.mano_IdxCode \r\n" +
						"     from (((td_MainObject mo \r\n" +
						"     left join td_BudgetNode b \r\n" +
						"     on  mo.maob_ProjectID = b.buno_ProjectID\r\n" +
						"     and mo.maob_ManageNodeID = b.buno_ManageNodeID\r\n" +
						"     and mo.maob_NodeID = b.buno_BudgetNodeID)\r\n" +
						"     left join td_ManageNode mn \r\n" +
						"     on  mo.maob_ProjectID = mn.mano_ProjectID \r\n" +
						"     and mo.maob_ManageNodeID = mn.mano_ManageNodeID) \r\n" +
						"     left join (select * from td_ManageNode where mano_Type=1) mnp \r\n" +
						"     on  mn.mano_ProjectID = mnp.mano_ProjectID\r\n" +
						"     and mn.mano_ProjectID = mnp.mano_ManageNodeID)\r\n" +
						"     where mo.maob_ProjectID = :projectId\r\n" +
						"     and exists(select 1 from td_business where busi_Type=2 and busi_ProjectID=mo.maob_ProjectID and busi_SWMethodID=mo.maob_SWMethodID) \r\n" +
						"     and mo.maob_Type = 0 \r\n" +
						"     order by mn.mano_IdxCode, b.buno_IdxCode",
				MapUtil.create().putValue("projectId", beSectionInfo.getTdProjectid()).getMap());
	}

	/**
	 * 清单抽取
	 * @param tdProjectId 招标文件项目id
	 */
	@Override
	public void extractBudgetItem(String tdProjectId) throws Exception {
		// 查询需要抽取的清单数量 0:招标, 1:评标, 2:开标
		Integer count = jdbcTemplateService.selectForObject(
				"select count(1) from td_mainobject where maob_ProjectID =:projectId and ifnull(maob_source, 0) = 0",
				MapUtil.create().putValue("projectId", tdProjectId).getMap(),Integer.class);
		//招标设置了清单,才需要抽取
		if (count > 0) {
			// 查询商务标方法
			Map<String, Object> bussinessInfoMap = jdbcTemplateService.selectForMap(
					"select busi_SWMethodID from td_business where busi_projectid=:projectId and busi_type=2",
					MapUtil.create().putValue("projectId", tdProjectId).getMap());
			if (bussinessInfoMap == null) {
				throw new Exception("方法不存在");
			}
			//抽取清单
			jdbcTemplateService.insert(
					"insert into td_mainobject(maob_projectid, maob_swmethodid, maob_managenodeid, \n" +
							"                 maob_nodeid, maob_name, maob_type, maob_idx, maob_balance, maob_source) \n" +
							"                 select a.buno_projectid, :swmethodId as maob_swmethodid, a.buno_managenodeid, \n" +
							"                  a.buno_budgetnodeid, a.buno_name, 0, 0, 1, 1 \n" +
							"                from td_budgetnode a \n" +
							"                where a.buno_projectid = :projectId \n" +
							"                  and a.buno_type = 2 \n" +
							"                  and not exists (select 1 from td_mainobject \n" +
							"                                 where maob_projectid = :projectId \n" +
							"                                   and maob_swmethodid = :swmethodId\n" +
							"                                   and maob_projectid = a.buno_projectid\n" +
							"                                   and maob_managenodeid = a.buno_managenodeid\n" +
							"                                   and maob_nodeid = a.buno_budgetnodeid)\n" +
							"               order by RAND() limit :count ",
					MapUtil.create().putValue("projectId", tdProjectId).putValue("swmethodId",
							bussinessInfoMap.get("busi_SWMethodID")).putValue("count", count).getMap());
		}
	}

	/**
	 * 查询需要抽取的清单信息
	 * @return
	 */
	@Override
	public List<Map<String, Object>> queryNeedExtractInfo() {
		return jdbcTemplateService.selectForList(
				"select a.td_projectid tdProjectId from be_section_info a\n" +
						"JOIN td_business b on a.td_projectId = b.busi_ProjectID and b.busi_type=2\n" +
						"LEFT JOIN (select count(1) count,maob_ProjectID from td_mainobject where IFNULL(maob_source,0)=1 GROUP BY maob_ProjectID) c\n" +
						"on a.td_projectid=c.maob_ProjectID where IFNULL(c.count,0) = 0 and date(a.bid_open_time) = curdate()",
				MapUtil.create().getMap());
	}


	/**
	 * 清单数据推送
	 * @return
	 */
	@Override
	@Transactional
	public void pushBudgetInfo() throws Exception {
		//查询今日开标需要推送的项目信息数据
		List<Map<String, Object>> sectionInfoList =
				jdbcTemplateService.selectForList("select td_ProjectId as projectId from be_section_info a join td_project b on a.td_projectId = b.proj_projectid " +
						"where date(a.bid_open_time) = curdate() and a.is_node_push=0",MapUtil.create().getMap());
		if(sectionInfoList != null && sectionInfoList.size() > 0) {
			for(Map<String, Object> projectMap :sectionInfoList) {
				List<Map<String, Object>> tdBidInfoList =
						jdbcTemplateService.selectForList("select enterprise_id from td_bidinfo where biin_projectid = :projectId",projectMap);
				//查询是否有投标单位导入，有1家导入就推送清单数据
				if(tdBidInfoList != null && tdBidInfoList.size() > 0) {
					//查询需要推送的清单数据
					List<Map<String, Object>> list = jdbcTemplateService.selectForList(
							"select CONCAT(@rownum:=@rownum+1,'') as xh, b.proj_ProjectID projectId, b.proj_Code SegmentShowId,b.proj_Name SegmentName,c.buno_Code Qdbh,a.maob_Name Qdmc,\n" +
									" c.buno_JobIdentity Xmtz,c.buno_Unit Jldw,ifnull(c.buno_Amount,0) Gcl, ifnull(c.buno_BidPriceBudg,0) Zhdj\n" +
									" from td_mainobject a\n" +
									" LEFT JOIN td_project b ON a.maob_projectid=b.proj_ProjectID\n" +
									" LEFT JOIN td_budgetnode c on a.maob_projectid=c.buno_ProjectID AND a.maob_ManageNodeId=c.buno_ManageNodeId AND a.maob_NodeId=c.buno_BudgetNodeID,(select @rownum:=0) e\n" +
									" where IFNULL(a.maob_source,0)=1 and b.proj_ProjectID=:projectId",
							projectMap);
					try {
						if (list != null && list.size() > 0) {
							log.info("开始推送清单，清单数据：" + GsonUtil.toJson(list));
							Response<String> response = bidParamService.sendList(list);
							if (response.isSuccess()) {
								//推送成功后更新标识
								jdbcTemplateService.update("update be_section_info set is_node_push =1 where td_projectId=:projectId",
										projectMap);
							} else {
								log.error("清单数据推送失败:" + response.getError());
							}
						}
					} catch (Exception e) {
						log.error("清单数据推送失败", e);
					}
				}
			}
		}
	}
}
